package com.dy.lock.screen.component.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.dy.lock.screen.component.DiscoverBannerComponent;
import com.dy.lock.screen.constants.TransmissionCode;
import com.dy.lock.screen.exception.ServerDisponseException;
import com.dy.lock.screen.pojo.DiscoverBannerInfo;
import com.dy.lock.screen.scoket.Head;
import com.dy.lock.screen.service.DiscoverBannerService;
import com.dy.lock.screen.utils.CommonUtil;
import com.dy.lock.screen.vo.DiscoverBannerVo;
import com.google.gson.Gson;

@Component("discoverBannerComponent")
public class DiscoverBannerComponentImpl implements DiscoverBannerComponent {
	private static final Logger log = Logger
			.getLogger(DiscoverBannerComponentImpl.class);
	private Gson gson;

	@Resource(name = "discoverBannerService")
	private DiscoverBannerService discoverBannerService;

	public DiscoverBannerComponentImpl() {
		gson = CommonUtil.gson();
	}

	@Override
	public List<DiscoverBannerInfo> list(String body, Head head) {
		DiscoverBannerVo vo = gson.fromJson(body, DiscoverBannerVo.class);
		if (vo != null) {
			Integer currentPage = vo.getPageIndex();
			Integer pageSize = vo.getPageCount();
			Integer pageStart = 1;
			Integer pageEnd = 10;
			if (currentPage != null && pageSize != null) {
				pageStart = (currentPage - 1) * pageSize + 1;
				pageEnd = currentPage * pageSize;
			}
			Map<String, Object> paraMap = new HashMap<String, Object>();
			paraMap.put("pageStart", pageStart);
			paraMap.put("pageEnd", pageEnd);
			List<DiscoverBannerInfo> disList = this.discoverBannerService
					.queryPage(paraMap);
			if (disList != null && !disList.isEmpty()) {
				for (DiscoverBannerInfo dis : disList) {
					if (StringUtils.isNoneBlank(dis.getDiscoverPic())) {
						dis.setDiscoverPic(CommonUtil.getUrlPrefix()
								+ dis.getDiscoverPic());
					}
				}
				return disList;
			} else {
				return new ArrayList<DiscoverBannerInfo>();
			}

		} else {
			log.info("requestId:" + head.getRequestId()
					+ ",获取发现页banner列表时，报文解析异常。");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}
	}

}
